<template>
  <div class="file-manage-page">
    <HeaderNav />
    <div class="file-manage-container">
      <div class="file-header">
        <h2>文件管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="handleUpload">上传文件</el-button>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedFiles.length === 0">批量删除</el-button>
        </div>
      </div>

      <div class="file-filter">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="文件名">
            <el-input v-model="filterForm.name" placeholder="请输入文件名" />
          </el-form-item>
          <el-form-item label="文件类型">
            <el-select v-model="filterForm.type" placeholder="请选择文件类型" clearable>
              <el-option
                v-for="file in fileArys"
                :key="file.value"
                :label="file.label"
                :value="file.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="file-table">
        <el-table
          :data="fileList"
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="original_name" label="文件名" min-width="200">
            <template #default="{ row }">
              <div class="file-name-cell">
                <el-icon class="file-icon">
                  <Document />
                </el-icon>
                <span class="file-name">{{ row.original_name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="文件类型" width="150" />
          <el-table-column prop="size" label="文件大小" width="120">
            <template #default="{ row }">
              {{ formatFileSize(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploader_name" label="上传者" width="120" />
          <el-table-column prop="created_at" label="上传时间" width="200">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handlePreview(row)">预览</el-button>
              <el-button type="primary" link @click="handleDownload(row)">下载</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="file-pagination">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="pagination.currentPage = $event"
          @update:page-size="pagination.pageSize = $event"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 文件上传弹窗 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文件"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        multiple
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            文件大小不能超过10MB
          </div>
        </template>
      </el-upload>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading">上传</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文件预览弹窗 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="previewFile.original_name"
      width="80%"
      top="50px"
      destroy-on-close
    >
      <div class="preview-content" style="text-align: center; max-height: 70vh; overflow: auto;">
        <!-- 图片预览 -->
        <img
          v-if="isImageFile(previewFile)"
          :src="previewFile.url"
          alt="预览图片"
          style="max-width: 100%; max-height: 70vh;"
          @error="handleImageError"
        />

        <!-- PDF预览 -->
        <iframe
          v-else-if="isPdfFile(previewFile)"
          :src="previewFile.url"
          style="width: 100%; height: 70vh; border: none;"
          @error="handlePreviewError"
        ></iframe>

        <!-- 视频预览 -->
        <video
          v-else-if="isVideoFile(previewFile)"
          :src="previewFile.url"
          controls
          style="max-width: 100%; max-height: 70vh;"
          @error="handlePreviewError"
        ></video>

        <!-- 音频预览 -->
        <audio
          v-else-if="isAudioFile(previewFile)"
          :src="previewFile.url"
          controls
          style="width: 100%; margin-top: 20px;"
          @error="handlePreviewError"
        ></audio>

        <!-- 文本文档预览 -->
        <div v-else-if="isTextFile(previewFile)" style="text-align: left; padding: 20px;">
          <pre style="white-space: pre-wrap; word-wrap: break-word;">{{ textContent }}</pre>
        </div>

        <!-- 不支持预览的文件类型 -->
        <div v-else style="padding: 20px;">
          <p>该文件类型不支持在线预览</p>
          <el-button type="primary" @click="handleDownload(previewFile)">下载文件</el-button>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownload(previewFile)">下载</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, UploadFilled } from '@element-plus/icons-vue'
import HeaderNav from '@/components/HeaderNav.vue'
import { getFileList, uploadFile, deleteFile, deleteFiles } from '@/api/files'

// 数据状态
const fileList = ref([])
const loading = ref(false)
const selectedFiles = ref([])
const uploadDialogVisible = ref(false)
const uploading = ref(false)
const uploadFiles = ref([])

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = ref({
  name: '',
  type: ''
})
//文件下拉选项
const fileArys = ref([
  {
    label: '图片',
    value: 'image'
  },
  {
    label: '文档',
    value: 'document'
  },
  {
    label: '视频',
    value: 'video'
  },

  {
    label: '音频',
    value: 'audio'
  },
   {
    label: '其他',
    value: 'other'
  },
])
// 获取文件列表
const fetchFileList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      name: filterForm.value.name,
      type: filterForm.value.type
    }

    const response = await getFileList(params)
    if (response.code === 200) {
      fileList.value = response.data.list
      pagination.value.total = response.data.pagination.total
    } else {
      ElMessage.error(response.message || '获取文件列表失败')
    }
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error('获取文件列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchFileList()
}

// 重置搜索
const handleReset = () => {
  filterForm.value.name = ''
  filterForm.value.type = ''
  pagination.value.currentPage = 1
  fetchFileList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  fetchFileList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchFileList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedFiles.value = selection
}

// 处理上传
const handleUpload = () => {
  uploadDialogVisible.value = true
  uploadFiles.value = []
}

// 处理文件选择变化
const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList
}

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  uploadFiles.value = fileList
}

// 提交上传
const submitUpload = async () => {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true
  try {
    // 创建FormData对象
    const formData = new FormData()
    uploadFiles.value.forEach(file => {
      formData.append('file', file.raw)
    })

    // 上传文件
    const response = await uploadFile(formData)
    if (response.code === 201) {
      ElMessage.success('文件上传成功')
      uploadDialogVisible.value = false
      // 重新获取文件列表
      fetchFileList()
    } else {
      ElMessage.error(response.message || '文件上传失败')
    }
  } catch (error) {
    ElMessage.error('文件上传失败')
    console.error('文件上传失败:', error)
  } finally {
    uploading.value = false
  }
}

// 处理下载
const handleDownload = async (row) => {
  try {
    // 创建一个隐藏的a标签来触发下载
    const link = document.createElement('a')
    link.href = row.url
    link.download = row.original_name
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('文件下载失败')

    // 如果直接下载失败，尝试打开新窗口
    try {
      window.open(row.url, '_blank')
    } catch (openError) {
      console.error('打开新窗口失败:', openError)
      ElMessage.error('无法下载或打开文件，请检查文件是否存在')
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除文件 "${row.original_name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteFile(row.id)
      if (response.code === 200) {
        ElMessage.success('文件删除成功')
        // 重新获取文件列表
        fetchFileList()
      } else {
        ElMessage.error(response.message || '文件删除失败')
      }
    } catch (error) {
      ElMessage.error('文件删除失败')
      console.error('文件删除失败:', error)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedFiles.value.map(file => file.id)
      const response = await deleteFiles(ids)
      if (response.code === 200) {
        ElMessage.success(response.message || '文件删除成功')
        // 清空选择
        selectedFiles.value = []
        // 重新获取文件列表
        fetchFileList()
      } else {
        ElMessage.error(response.message || '文件删除失败')
      }
    } catch (error) {
      ElMessage.error('文件删除失败')
      console.error('文件删除失败:', error)
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 预览相关
const previewDialogVisible = ref(false)
const previewFile = ref({})
const textContent = ref('')

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event)
  ElMessage.error('图片加载失败，可能文件不存在或路径错误')
}

// 处理预览错误
const handlePreviewError = (event) => {
  console.error('文件预览失败:', event)
  ElMessage.error('文件预览失败，请尝试下载文件')
}

// 处理预览
const handlePreview = async (row) => {
  previewFile.value = row
  textContent.value = ''

  // 如果是文本文档，获取文件内容（指定编码以避免乱码）
  if (isTextFile(row)) {
    try {
      const response = await fetch(row.url, {
        headers: {
          'Accept': 'text/plain;charset=utf-8'
        }
      })
      // 指定UTF-8编码以避免乱码
      const buffer = await response.arrayBuffer()
      const decoder = new TextDecoder('utf-8')
      textContent.value = decoder.decode(buffer)
    } catch (error) {
      console.error('获取文件内容失败:', error)
      ElMessage.error('文件内容加载失败')
    }
  }

  previewDialogVisible.value = true
}

// 判断是否为图片文件
const isImageFile = (file) => {
  // 检查文件类型或文件扩展名
  return file.type.startsWith('image/') ||
         /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.original_name)
}

// 判断是否为PDF文件
const isPdfFile = (file) => {
  return file.type === 'application/pdf' ||
         /\.pdf$/i.test(file.original_name)
}

// 判断是否为视频文件
const isVideoFile = (file) => {
  return file.type.startsWith('video/') ||
         /\.(mp4|avi|mov|wmv|flv|mkv)$/i.test(file.original_name)
}

// 判断是否为音频文件
const isAudioFile = (file) => {
  return file.type.startsWith('audio/') ||
         /\.(mp3|wav|ogg|flac|aac)$/i.test(file.original_name)
}

// 判断是否为文本文档
const isTextFile = (file) => {
  const textTypes = [
    'text/plain',
    'text/html',
    'text/css',
    'text/javascript',
    'application/javascript',
    'application/json',
    'application/xml'
  ]
  return textTypes.includes(file.type)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchFileList()
})
</script>

<style scoped lang="scss">
.file-manage-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.file-manage-container {
  padding: 20px;
}

.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  h2 {
    margin: 0;
    font-size: 24px;
    color: #333;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.file-filter {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;

  .filter-form {
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
}

.file-table {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;

  .file-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;

    .file-icon {
      font-size: 16px;
      color: #409eff;
    }

    .file-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.file-pagination {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  :deep(.el-upload) {
    display: block;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
  }
}
</style>
